package com.smarthouse.controller;

import com.alibaba.fastjson.JSON;
import com.smarthouse.model.ApiResponse;
import com.smarthouse.model.IdCardDetectRequest;
import com.smarthouse.model.IdCardDetectResponse;
import com.smarthouse.service.IdCardService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Tag(name = "身份证识别接口")
@RestController
@RequestMapping("/idcard")
@CrossOrigin
public class IdCardController {
    private static final Logger logger = LoggerFactory.getLogger(IdCardController.class);

    @Autowired
    private IdCardService idCardService;

    @Operation(summary = "身份证识别")
    @PostMapping("/detect")
    public ApiResponse<IdCardDetectResponse> detectIdCard(@RequestBody IdCardDetectRequest request) {
        logger.info("收到身份证识别请求 - 请求路径: /api/idcard/detect");
        try {
            if (request == null || request.getImage1Base64() == null) {
                logger.error("请求参数为空");
                return ApiResponse.error("请求参数不能为空");
            }

            String imagePreview = request.getImage1Base64().substring(0, Math.min(100, request.getImage1Base64().length()));
            logger.info("收到图片数据(前100字符): {}", imagePreview);

            logger.info("开始调用百度身份证识别服务");
            IdCardDetectResponse response = idCardService.detectIdCard(request.getImage1Base64());
            logger.info("身份证识别完成, 返回数据: {}", JSON.toJSONString(response));

            ApiResponse<IdCardDetectResponse> apiResponse = ApiResponse.success(response);
            logger.info("最终返回数据: {}", JSON.toJSONString(apiResponse));
            
            return apiResponse;
        } catch (Exception e) {
            logger.error("身份证识别失败", e);
            return ApiResponse.error(e.getMessage());
        }
    }
} 